#include "objreader.hpp"
namespace chen {

void loadTriangleMesh (std::vector<const Shape*> * ret, const char * fname, const Transform * trc, const Material * matr) {
    LOG(INFO) << "[loader] loading file " << fname;
    FILE * fin = fopen(fname, "r");
    char * ln = new char[1024];
    std::vector<Point3> verts;
    Bound3 bnd;
    bool bndflg = false;
    while(fgets(ln, 1024u, fin)) {
        if(ln[0] == '#') continue ;
        char cmd[24];
        if(sscanf(ln, "%s", cmd) != 1) break ;
        if(strcmp(cmd, "v") == 0) {
            double a, b, c;
            sscanf(ln, "%*s%lf%lf%lf", &a, &b, &c);
            verts.push_back(Point3(a, b, c));
            if(bndflg) bnd = combine(bnd, Bound3(Point3(a, b, c)));
            else bnd = Bound3(Point3(a, b, c)), bndflg = true;
        }
        if(strcmp(cmd, "f") == 0) {
            int a, b, c, d;
            int rd = sscanf(ln, "%*s%d%d%d%d", &a, &b, &c, &d);
            if(rd >= 3)
                ret->push_back(
                    (Shape*)(new Triangle(
                        &transform_unit,
                        matr,
                        trc->reversed(verts[a-1]),
                        trc->reversed(verts[b-1]),
                        trc->reversed(verts[c-1])
                    ))
                );
            if(rd >= 4) 
                ret->push_back(
                    new Triangle(
                        &transform_unit,
                        matr,
                        trc->reversed(verts[a-1]),
                        trc->reversed(verts[d-1]),
                        trc->reversed(verts[c-1])
                    )
                );
        }
        if(feof(fin)) break ;
    }
    LOG(INFO) << "[loader] loading file " << fname << " complete, verts:" << verts.size();
}

}